<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderNo">
              <a-input v-model="model.orderNo" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplyId">
              <j-search-select-tag v-model="model.supplyId" dict="mdm_supply,supply_full_name,id"  />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="订单日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderDate">
              <j-date placeholder="请选择订单日期" v-model="model.orderDate" style="width: 100%" @change="orderDateChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId_dictText">
              <j-popup
                v-model="model.projectId_dictText"
                field="projectId"
                org-fields="id,project_name"
                dest-fields="projectId,projectId_dictText"
                code="quote_project_popup"
                :multi="false"
                @input="projectPopupCallback"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="采购员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="buyer">
              <yq-select-user-by-dep v-model="model.buyer" text="realname,orgCodeTxt" :multi="false" @change="buyerChanged"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="订单类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderType">
              <j-dict-select-tag type="list" v-model="model.orderType" dictCode="mm_purchase_type" placeholder="请选择订单类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="优惠率%" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reduceRate">
              <a-input-number v-model="model.reduceRate" placeholder="请输入优惠率" style="width: 100%" @change="reduceRateChanged"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="优惠金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reducePrice">
              <a-input-number v-model="model.reducePrice" placeholder="请输入优惠金额" style="width: 100%" @change="reducePriceChanged"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="优惠后金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="totalActPrice">
              <a-input-number v-model="model.totalActPrice" placeholder="请输入优惠后金额" style="width: 100%" @change="totalActPriceChanged"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="16">
            <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="remark">
              <a-textarea v-model="model.remark" rows="2" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="订单明细" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="mmPurchaseOrderDetailTable.loading"
          :columns="mmPurchaseOrderDetailTable.columns"
          :dataSource="mmPurchaseOrderDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          :actionAddButton="false"
          :disabledRows="mmPurchaseOrderDetailTable.disabledRows"
          @added = "detailAdded"
          @valueChange = "qtyAndPriceChange">

          <div slot="buttonBefore" >
            <div class="action-button">
              <a-button slot="buttonBefore" type="primary" icon="plus" @click="choosePurchaseRequisition" :disabled="formDisabled">选单</a-button>
              <span class="gap"></span>
              <a-button slot="buttonBefore" type="primary" icon="plus" @click="chooseMaterial" :disabled="formDisabled">新增</a-button>
              <span class="gap"></span>
              <a-button slot="buttonBefore" icon="redo" @click="chooseLatestPriceSupply" :disabled="formDisabled">获取最近采购价</a-button>
              <span class="gap"></span>
            </div>
          </div>
        </j-editable-table>
        <j-popup-onl-report ref="reqPopReport" code="mm_req_pop" multi="true" :param="reqPopupParam" @ok="reqPopupCallback"/>
        <j-popup-onl-report ref="materialPopReport" code="mdm_popup_bom_material" :param="materialPopupParam" multi="true" @ok="materialPopupCallback"/>
        <j-modal
          title="获取最近采购价"
          :width="400"
          :visible="latestPriceModalVisible"
          switchFullscreen
          @ok="getLatestPrice"
          :okButtonProps="{ class:{'jee-hidden': false} }"
          @cancel="cancelLatestPrice"
          cancelText="关闭">
            <a-form-model ref="latestPriceForm">
              <a-row>
                <a-col :span="24">
                  <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplyType">
                    <a-radio-group v-model="supplyType">
                      <a-radio :value="1">
                        当前供应商
                      </a-radio>
                      <a-radio :value="2">
                        所有供应商
                      </a-radio>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
        </j-modal>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import store from '@/store'
  import moment from "moment";
  import {isNumber} from "@/utils/util";

  export default {
    name: 'MmPurchaseOrderForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
          status: '01',
          orderType: '01',
          orderDate: moment(new Date()).format('YYYY-MM-DD'),
          buyer: store.getters.userInfo.username,
          buyerDept: store.getters.userInfo.orgCode,
          reduceRate: 0,
          reducePrice: 0,
          totalActPrice: 0,
        },
        reqPopupParam: {},
        materialPopupParam: {},
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           supplyId: [
              { required: true, message: '请输入供应商!'},
           ],
          orderDate: [
            { required: true, message: '请输入订单日期!'},
          ],
        },
        refKeys: ['mmPurchaseOrderDetail', ],
        tableKeys:['mmPurchaseOrderDetail', ],
        activeKey: 'mmPurchaseOrderDetail',
        // 采购订单明细
        mmPurchaseOrderDetailTable: {
          loading: false,
          dataSource: [],
          disabledRows: {},
          columns: [
            {
              title: '物料描述',
              key: 'materialDesc',
              type: FormTypes.popup,
              popupCode:"mdm_popup_bom_material",
              orgFields: 'material_id,material_code,material_desc,material_unit_code,null_value',
              destFields: 'materialId,materialNo,materialDesc,unit,reqDetailId',
              width:"260px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '单位',
              key: 'unit',
              type: FormTypes.sel_search,
              dictCode:"mdm_unit,unit_name,unit_code",
              width:"110px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '订单数量',
              key: 'purQty',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              statistics: true,
              scale: 2,
              validateRules: [
                { required: true, message: '${title}不能为空' },
                { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '请输入大于零的数' },
                { handler(type, value, row, column, callback, target){
                    let {values} = target.getValuesSync({ validate: false, rowIds: [row.id] });
                    if(values[0].reqDetailId){
                      if( type === 'blur' || type === 'getValues'){
                        if(Number(value) > Number(values[0].maxPurQty)){
                          callback(false, '${title}不能超出最大可采购量：'+ values[0].maxPurQty)
                          return
                        }else{
                          callback(true)
                        }
                      }else{
                        callback();
                      }
                    }else{
                      callback();
                    }
                  },
                },
              ],
            },
            {
              title: '含税单价',
              key: 'unitPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
            },
            {
              title: '折扣率%',
              key: 'discountRate',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
            },
            {
              title: '折扣额',
              key: 'discountPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              statistics: true,
              scale: 2,
            },
            {
              title: '购货金额',
              key: 'actPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              statistics: true,
              scale: 2,
            },
            {
              title: '含税金额',
              key: 'sumPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              statistics: true,
              scale: 2,
              validateRules: [
                { required: true, message: '${title}不能为空' },
                { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '请输入大于零的数' },
              ],
            },
            {
              title: '税率',
              key: 'taxRate',
              type: FormTypes.sel_search,
              dictCode:"mdm_tax_rate,value,value",
              width:"110px",
              placeholder: '请输入${title}',
              defaultValue:'0.13',
            },
            {
              title: '税额',
              key: 'taxPrice',
              type: FormTypes.inputNumber,
              width:"110px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              statistics: true,
              scale: 2,
            },
            {
              title: '交货日期',
              key: 'deliveryDate',
              type: FormTypes.date,
              width:"160px",
              placeholder: '请输入${title}',
              defaultValue: moment(new Date()).format('YYYY-MM-DD'),
            },
            {
              title: '备注',
              key: 'remark',
              type: FormTypes.input,
              width:"240px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '行号',
              key: 'lineNo',
              type: FormTypes.inputNumber,
              width:"70px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: 'materialId',
              key: 'materialId',
              type:"hidden"
            },
            {
              title: 'materialNo',
              key: 'materialNo',
              type:"hidden"
            },
            {
              title: 'status',
              key: 'status',
              type:"hidden",
              defaultValue: '01'
            },
            {
              title: 'inQty',
              key: 'inQty',
              type:"hidden",
              defaultValue: '0'
            },
            {
              title: 'reqDetailId',
              key: 'reqDetailId',
              type:"hidden",
            },
            {
              title: 'pid',
              key: 'pid',
              type:"hidden",
            },
            {
              title: 'maxPurQty',
              key: 'maxPurQty',
              type:"hidden",
              defaultValue: 0
            },
          ]
        },
        url: {
          add: "/mm/purchaseOrder/add",
          edit: "/mm/purchaseOrder/edit",
          queryById: "/mm/purchaseOrder/queryById",
          genCode: "/mdm/codeRule/genCode",
          queryLatestPrice: "/mm/purchaseOrder/queryLatestPrice",
          sysUserList:"/sys/user/queryUserComponentData",
          sysUserDepInfo: "/sys/user/queryDepInfoByUsername",
          mmPurchaseOrderDetail: {
            list: '/mm/purchaseOrder/queryDetailListByMainId'
          },
        },
        latestPriceModalVisible: false,
        supplyType: 1
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      addBefore(){
        this.genPurNo();
        this.mmPurchaseOrderDetailTable.dataSource=[]
      },
      genPurNo(){
        this.confirmLoading = true
        getAction(this.url.genCode, {codeType: '15'}).then(res => {
          if (res.success) {
            this.model.orderNo = res.result;
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      editBefore(record){
        record.id = record.pid;
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.mmPurchaseOrderDetail.list, params, this.mmPurchaseOrderDetailTable, this.setDisableRow)
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          mmPurchaseOrderDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      buyerChanged(value){
        if(value){
          let that = this;
          let params = {username: value};
          getAction(this.url.sysUserDepInfo, params).then((res) => {
            if (res.success) {
              if(res.result){
                that.model['buyerDept'] = res.result.orgCodes.split(',',1)[0];
              }
            }
          })
        }
      },
      reduceRateChanged(value){
        if(value){
          let detailActPrice = this.model.detailActPrice || 0;
          let reducePrice = this.$math.round(this.$math.multiply(detailActPrice, value));
          this.model.reducePrice = reducePrice;
          this.model.totalActPrice = this.$math.round(this.$math.subtract(detailActPrice, reducePrice));
        }
      },
      reducePriceChanged(value){
        if(!isNumber(value)){
          this.model.reducePrice = 0;
        }
        value = this.model.reducePrice;
        let detailActPrice = this.model.detailActPrice || 0;
        let reduceRate = 0;
        if(detailActPrice != 0){
          reduceRate = this.$math.round(this.$math.multiply(this.$math.divide(value, detailActPrice), 100));
        }
        this.model.reduceRate = reduceRate;
        this.model.totalActPrice = this.$math.round(this.$math.subtract(detailActPrice, value));
      },
      totalActPriceChanged(value){
        if(!isNumber(value)){
          this.model.totalActPrice = 0;
        }
        value = this.model.totalActPrice;
        let detailActPrice = this.model.detailActPrice || 0;
        let reducePrice = this.$math.round(this.$math.subtract(detailActPrice, value));
        let reduceRate = 0;
        if(detailActPrice != 0){
          reduceRate = this.$math.round(this.$math.multiply(this.$math.divide(reducePrice, detailActPrice), 100));
        }
        this.model.reducePrice = reducePrice;
        this.model.reduceRate = reduceRate;
      },
      qtyAndPriceChange(parm){
        if(parm && parm['column'] && parm['row'] && parm['target']){
          let cols = ['purQty','sumPrice','unitPrice','taxRate','taxPrice','discountRate','discountPrice','actPrice'];
          let key = parm.column.key;
          if(cols.includes(key)){
            let editableTable = parm['target'];
            // 重新计算当前行金额、税额、折扣额、购货金额
            if(key === cols[0] || key === cols[2]){
              let unitPrice = parm.row[cols[2]] || 0;
              let purQty = parm.row[cols[0]] || 0;
              let taxRate = parm.row[cols[3]] || 0;
              let discountRate = parm.row[cols[5]] || 0;
              let sumPrice = this.$math.round(this.$math.multiply(unitPrice , purQty));
              let taxPrice = this.$math.round(this.$math.divide(this.$math.multiply(sumPrice , taxRate),this.$math.add(1, taxRate)));
              let discountPrice = this.$math.round(this.$math.multiply(this.$math.divide(discountRate, 100), sumPrice));
              let actPrice = this.$math.subtract(sumPrice, discountPrice);
              let values = {[cols[1]]: sumPrice, [cols[4]]: taxPrice, [cols[6]]: discountPrice, [cols[7]]: actPrice}
              editableTable.setValues([{rowKey: parm.row.id, values: values}]);
            }
            // 重新计算单价、税额、折扣额、购货金额
            if(key === cols[1]){
              let sumPrice = parm.row[cols[1]] || 0;
              let purQty = parm.row[cols[0]] || 0;
              let discountRate = parm.row[cols[5]] || 0;
              if(purQty != 0){
                let unitPrice = Math.round(sumPrice / purQty * 100)/100;
                editableTable.setValues([{rowKey: parm.row.id, values: {[cols[2]]: unitPrice}}]);
              }
              let taxRate = parm.row[cols[3]] || 0;
              let taxPrice = Math.round(sumPrice * taxRate * 100 / (1 + Number(taxRate)))/100;
              let discountPrice = this.$math.round(this.$math.multiply(this.$math.divide(discountRate, 100), sumPrice));
              let actPrice = this.$math.subtract(sumPrice, discountPrice);
              editableTable.setValues([{rowKey: parm.row.id, values: {[cols[4]]: taxPrice, [cols[6]]: discountPrice, [cols[7]]: actPrice}}]);
            }
            // 重新计算税额
            if(key === cols[3]){
              let sumPrice = parm.row[cols[1]] || 0;
              let taxRate = parm.row[cols[3]] || 0;
              let taxPrice = Math.round(sumPrice * taxRate * 100 /(1 + Number(taxRate)))/100;
              editableTable.setValues([{rowKey: parm.row.id, values: {[cols[4]]: taxPrice}}]);
            }
            // 重新计算折扣额、购货金额
            if(key === cols[5]){
              let sumPrice = parm.row[cols[1]] || 0;
              let discountRate = parm.row[cols[5]] || 0;
              let discountPrice = this.$math.round(this.$math.multiply(this.$math.divide(discountRate, 100), sumPrice));
              let actPrice = this.$math.subtract(sumPrice, discountPrice);
              editableTable.setValues([{rowKey: parm.row.id, values: {[cols[6]]: discountPrice, [cols[7]]: actPrice}}]);
            }
            // 重新计算折扣率、购货金额
            if(key === cols[6]){
              let sumPrice = parm.row[cols[1]] || 0;
              let discountPrice = parm.row[cols[6]] || 0;
              let discountRate = 0;
              if(sumPrice != 0){
                discountRate = this.$math.round(this.$math.multiply(this.$math.divide(discountPrice, sumPrice), 100));
              }
              let actPrice = this.$math.subtract(sumPrice, discountPrice);
              editableTable.setValues([{rowKey: parm.row.id, values: {[cols[5]]: discountRate, [cols[7]]: actPrice}}]);
            }
            // 重新计算折扣率、折扣额
            if(key === cols[7]){
              let sumPrice = parm.row[cols[1]] || 0;
              let actPrice = parm.row[cols[7]] || 0;
              let discountPrice = this.$math.round(this.$math.subtract(sumPrice, actPrice));
              let discountRate = 0;
              if(sumPrice != 0){
                discountRate = this.$math.round(this.$math.multiply(this.$math.divide(discountPrice, sumPrice), 100));
              }
              editableTable.setValues([{rowKey: parm.row.id, values: {[cols[5]]: discountRate, [cols[6]]: discountPrice}}]);
            }
            // 重新计算统计列
            editableTable.recalcOneStatisticsColumn(cols[0]);
            editableTable.recalcOneStatisticsColumn(cols[1]);
            editableTable.recalcOneStatisticsColumn(cols[4]);
            editableTable.recalcOneStatisticsColumn(cols[6]);
            editableTable.recalcOneStatisticsColumn(cols[7]);
            // 更新主表总金额、明细折扣额、明细购货金额、实际总额、优惠率
            this.model.totalPrice = editableTable.getStatisticsValue(cols[1]) || 0;
            this.model.detailDiscountPrice = editableTable.getStatisticsValue(cols[6]) || 0;
            this.model.detailActPrice = editableTable.getStatisticsValue(cols[7]) || 0;
            let reducePrice = this.model.reducePrice || 0;
            this.model.totalActPrice = this.$math.round(this.$math.subtract(this.model.detailActPrice, reducePrice));
            let reduceRate = 0;
            if(this.model.detailActPrice != 0){
              reduceRate = this.$math.round(this.$math.multiply(this.$math.divide(reducePrice, this.model.detailActPrice), 100));
            }
            this.model.reduceRate = reduceRate;
          }
        }
      },
      detailAdded: function (obj) {
        this.autoLineNo(obj.row.id);
        this.detailAddInit(obj.row);
      },
      /** 自动生成行号 */
      autoLineNo(rowId){
        let editTable = this.$refs[this.refKeys[0]];
        let rows = editTable.rows;
        let num = 10;
        if(rows.length > 1){
          let lastId = editTable.getCleanId(rows[rows.length-2].id)
          let {values} = editTable.getValuesSync({ validate: false, rowIds: [lastId] });
          num = Number(values[0].lineNo) + 10
        }
        editTable.setValues([{rowKey: rowId, values:{lineNo: num}}])
      },
      detailAddInit(row){
        let editTable = this.$refs[this.refKeys[0]];
        let values = [
          {
            rowKey: row.id,
            values:{deliveryDate: this.model.orderDate}
          }
        ]
        editTable.setValues(values)
      },
      choosePurchaseRequisition(){
        let ids = this.getReqDetailIdsChoosed()
        this.reqPopupParam = {reqDetailIdList: ids, buyer: this.model.buyer, projectId: this.model.projectId}
        this.$refs.reqPopReport.show();
      },
      getReqDetailIdsChoosed(){
        let editTable = this.$refs[this.refKeys[0]];
        let {values} = editTable.getValuesSync({validate: false});
        let ids = "";
        if(values && values.length > 0){
          for(let reqDetail of values){
            let reqDetailId = reqDetail.reqDetailId
            if(reqDetailId){
              ids = ids + (ids ? ',' : '') + reqDetailId
            }
          }
        }
        return ids;
      },
      chooseMaterial(){
        let ids = this.getMaterialIdsChoosed()
        this.materialPopupParam = {materialIdList: ids, buyer: this.model.buyer}
        this.$refs.materialPopReport.show();
      },
      getMaterialIdsChoosed(){
        let editTable = this.$refs[this.refKeys[0]];
        let {values} = editTable.getValuesSync({validate: false});
        let ids = "";
        if(values && values.length > 0){
          for(let reqDetail of values){
            if(reqDetail.materialId){
              ids = ids + (ids ? ',' : '') + reqDetail.materialId
            }
          }
        }
        return ids;
      },
      getLatestPrice(){
        let that = this;
        let editTable = this.$refs[this.refKeys[0]];
        if(editTable.rows.length === 0){
          this.$message.error("请先添加订单明细");
          return;
        }
        let {values} = editTable.getValuesSync({validate: false});
        let materialIdArr = values.filter(data => data.materialId).map(data => data.materialId);
        if(!materialIdArr || materialIdArr.length == 0){
          this.$message.error("请先维护物料信息");
          return;
        }
        if(this.supplyType == 1 && !this.model.supplyId){
          this.$message.error("请先维护供应商");
          return;
        }
        this.latestPriceModalVisible = false;
        let supplyId = null;
        if(this.supplyType == 1){
          supplyId = this.model.supplyId;
        }
        let materialIds = materialIdArr.join(',')
        this.mmPurchaseOrderDetailTable.loading = true
        getAction(this.url.queryLatestPrice, {materialIds: materialIds, supplyId: supplyId}).then(res => {
          if (res.success) {
            let resData = res.result;
            for(let row of editTable.rows){
              let rowData = editTable.getValuesSync({validate: false, rowIds: [row.id]}).values[0];
              if(!rowData.materialId || !resData[rowData.materialId]){
                continue;
              }
              // 重新计算当前行单价、金额、税额、折扣额、购货金额
              let unitPrice = resData[rowData.materialId] || 0;
              let purQty = rowData.purQty || 0;
              let taxRate = rowData.taxRate || 0;
              let discountRate = rowData.discountRate || 0;
              let sumPrice = that.$math.round(that.$math.multiply(unitPrice , purQty));
              let taxPrice = that.$math.round(that.$math.divide(that.$math.multiply(sumPrice , taxRate),that.$math.add(1, taxRate)));
              let discountPrice = that.$math.round(that.$math.multiply(that.$math.divide(discountRate, 100), sumPrice));
              let actPrice = that.$math.subtract(sumPrice, discountPrice);
              let valueObj = {unitPrice: unitPrice, sumPrice: sumPrice, taxPrice: taxPrice, discountPrice: discountPrice, actPrice: actPrice}
              editTable.setValues([{rowKey: row.id, values: valueObj}]);
              // 重新计算统计列
              editTable.recalcOneStatisticsColumn('purQty');
              editTable.recalcOneStatisticsColumn('sumPrice');
              editTable.recalcOneStatisticsColumn('taxPrice');
              editTable.recalcOneStatisticsColumn('discountPrice');
              editTable.recalcOneStatisticsColumn('actPrice');
              // 更新主表总金额、明细折扣额、明细购货金额、实际总额、优惠率
              that.model.totalPrice = editTable.getStatisticsValue('sumPrice') || 0;
              that.model.detailDiscountPrice = editTable.getStatisticsValue('discountPrice') || 0;
              that.model.detailActPrice = editTable.getStatisticsValue('actPrice') || 0;
              let reducePrice = that.model.reducePrice || 0;
              that.model.totalActPrice = that.$math.round(that.$math.subtract(that.model.detailActPrice, reducePrice));
              let reduceRate = 0;
              if(that.model.detailActPrice != 0){
                reduceRate = that.$math.round(that.$math.multiply(that.$math.divide(reducePrice, that.model.detailActPrice), 100));
              }
              that.model.reduceRate = reduceRate;
            }
          }
        }).finally(() => {
          that.mmPurchaseOrderDetailTable.loading = false
        })
      },
      reqPopupCallback(rows){
        if(rows && rows.length > 0){
          let mmPurchaseOrderDetail = this.$refs[this.refKeys[0]];
          let oldData = mmPurchaseOrderDetail.getValuesSync();
          let column = this.mmPurchaseOrderDetailTable.columns.find(col=>col.key === 'materialDesc')
          let orgFieldsArr = ['id','material_id','material_no','material_desc','unit', 'qty','req_date','max_qty'];
          let destFieldsArr =['reqDetailId', 'materialId', 'materialNo', 'materialDesc', 'unit', 'purQty','deliveryDate','maxPurQty'];
          let addRow, addData
          for(let i =0; i< rows.length; i++){
            if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
              mmPurchaseOrderDetail.add();
            }
            addRow = mmPurchaseOrderDetail.rows[mmPurchaseOrderDetail.rows.length - 1];
            // key转换
            for(let j=0; j<orgFieldsArr.length; j++){
              rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
              if(destFieldsArr[j] !== orgFieldsArr[j]){
                delete rows[i][orgFieldsArr[j]]
              }
            }
            addData = Object.assign({},rows[i])
            mmPurchaseOrderDetail.popupCallback(addData.materialDesc, addData, 'materialDesc'+addRow.id, addRow, column)
          }
        }
      },
      materialPopupCallback(rows){
        if(rows && rows.length > 0){
          let mmPurchaseOrderDetail = this.$refs[this.refKeys[0]];
          let oldData = mmPurchaseOrderDetail.getValuesSync();
          let column = this.mmPurchaseOrderDetailTable.columns.find(col=>col.key === 'materialDesc')
          let orgFieldsArr = column.orgFields.split(',');
          let destFieldsArr = column.destFields.split(',');
          let addRow, addData
          for(let i =0; i< rows.length; i++){
            if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
              mmPurchaseOrderDetail.add();
            }
            addRow = mmPurchaseOrderDetail.rows[mmPurchaseOrderDetail.rows.length - 1];
            // key转换
            for(let j=0; j<orgFieldsArr.length; j++){
              rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
              if(destFieldsArr[j] !== orgFieldsArr[j]){
                delete rows[i][orgFieldsArr[j]]
              }
            }
            addData = Object.assign({},rows[i])
            mmPurchaseOrderDetail.popupCallback(addData.materialDesc, addData, 'materialDesc'+addRow.id, addRow, column)
          }
        }
      },
      handleValidOk(){
        let editTable = this.$refs[this.refKeys[0]];
        let rows = editTable.rows
        if(rows.length === 0){
          this.$message.warning("请输入采购明细！");
        }else{
          this.handleOk();
        }
      },
      orderDateChange(dateStr){
        if(!dateStr){
          return
        }
        let editTable = this.$refs[this.refKeys[0]];
        let rows = editTable.rows
        if(rows.length === 0){
          return
        }
        for(let row of rows){
          editTable.setValues([{rowKey: row.id, values:{deliveryDate: dateStr}}])
        }
      },
      setDisableRow(){
        let orderDetailData = this.mmPurchaseOrderDetailTable.dataSource;
        if(orderDetailData.length > 0){
          let ids = orderDetailData.filter(item => item.status !== '01').map(item => item.id)
          this.mmPurchaseOrderDetailTable.disabledRows.id = ids
        }
      },
      projectPopupCallback(value,row){
        this.model = Object.assign(this.model, row);
      },
      chooseLatestPriceSupply(){
        this.latestPriceModalVisible = true;
      },
      cancelLatestPrice(){
        this.latestPriceModalVisible = false;
      }
    }
  }
</script>

<style scoped>
  .action-button {
    margin-bottom: 8px;
  }
  .gap {
    padding-left: 8px;
  }
</style>